// pages/login/login.js
import {
  toast
} from "../../utils/extendApi"
//导入本地存储API
import {
  setStorage
} from "../../utils/storage"
//导入接口API函数
import {
  reqLogin,
  reqUserInfo
} from "../../api/user"
//导入ComponentWithStore方法
import {
  ComponentWithStore
} from "mobx-miniprogram-bindings"
//导入store对象
import {
  userStore
} from "../../stores/userStore"
//导入防抖函数
import {
  debounce
} from "miniprogram-licia"
ComponentWithStore({
  //让页面和store对象建立关联
  storeBindings: {
    store: userStore,
    fields: ["token", "userInfo"],
    actions: ["setToken", "setUserInfo"]
  },
  methods: {
    //授权登录
    login: debounce(function () {
      //获取用户临时登录凭证
      wx.login({
        success: async ({
          code
        }) => {

          if (code) {
            //获取到临时登录凭证code
            const {
              data
            } = await reqLogin(code)
            //登录成功以后，需要将服务器响应的自定义登录状态存储到本地
            setStorage("token", data.token)

            //将自定义登录状态token存储到store对象
            this.setToken(data.token)

            //获取用户信息
            this.getUserInfo()

            //返回上一级页面
            wx.navigateBack()

          } else {
            toast({
              title: "授权失败，请重新授权"
            })
          }

        },
      })
    }, 500),
    //获取用户信息
    async getUserInfo() {
      //调用接口，获取用户信息
      const {
        data
      } = await reqUserInfo()
      setStorage("userInfo", data)

      //将用户信息存储到Store
      this.setUserInfo(data)
    }
  }

})